Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何根据std::is_相同检查返回不同类型_C++_Templates - Fatal编程技术网

C++ 如何根据std::is_相同检查返回不同类型

C++ 如何根据std::is_相同检查返回不同类型,c++,templates,C++,Templates,考虑以下代码: template<typename T> T foo() { if (std::is_same<T, int>::value) return 5; if (std::is_same<T, std::string>::value) return std::string("bar"); throw std::exception(); } 模板 T foo(){ if(std::is_sa

考虑以下代码:

template<typename T>
T foo() {
    if (std::is_same<T, int>::value)
        return 5;

    if (std::is_same<T, std::string>::value)
        return std::string("bar");

    throw std::exception();
}
模板
T foo(){
if(std::is_same::value)
返回5;
if(std::is_same::value)
返回标准::字符串(“条”);
抛出std::exception();
}
当使用
foo()
调用时,它抛出一个错误
无法将'std::uuCxx11::string{aka std::uuCxx11::basic_string}'转换为'int'作为返回


我知道解决方案是使用模板专门化,但我想问的是,通过
std::is_same

的两个分支在编译时都必须有效,即使其中一个从未执行过

如果可以访问C++17,请将
If
s更改为
If constexpr

template<typename T>
T foo() {
    if constexpr (std::is_same<T, int>::value)
        return 5;

    if constexpr (std::is_same<T, std::string>::value)
        return std::string("bar");

    throw std::exception();
}
模板
T foo(){
如果constexpr(std::is_same::value)
返回5;
如果constexpr(std::is_same::value)
返回标准::字符串(“条”);
抛出std::exception();
}
在C++17之前,您必须使用模板专业化来模拟这一点:

template<typename T>
T foo()
{
    throw std::exception();
}

template <>
int foo<int>() {
    return 5;
}

template <>
std::string foo<std::string>() {
    return "bar";
}
模板
T foo()
{
抛出std::exception();
}
模板
int foo(){
返回5;
}
模板
std::stringfoo(){
返回“bar”;
}

如果您的real
foo
比这个示例做的工作更多,并且专门化它会导致代码重复,那么您可以引入一个helper函数,它将只封装
return
/
throw
语句,并专门化它。

在C++17编译器之前的版本中,您可以使用标记分派来获得所需的内容

template <typename T> tag_t {};

int foo(tag_t<int> t) { return 5; }

std::string foo(tag_t<std::string> t) { return "bar"; }

template<typename T>
T foo() {
    return foo(tag_t<T>());
}
模板标签{};
int foo(tag_t){return 5;}
std::stringfoo(标记){返回“bar”;}
模板
T foo(){
返回foo(tag_t());
}