Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.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++ C++;模板-浮动和整数类型的不同专门化_C++_C++11_Templates_Template Specialization - Fatal编程技术网

C++ C++;模板-浮动和整数类型的不同专门化

C++ C++;模板-浮动和整数类型的不同专门化,c++,c++11,templates,template-specialization,C++,C++11,Templates,Template Specialization,我正在尝试编写一个签名如下的函数: template<typename From, typename To> To bar(From in){...} 模板 禁止(从中){…} 此函数需要具有不同的行为,具体取决于to是浮动类型还是整数类型。(假设来自的为整数,且两者均为算术) 这可以通过使用if constexpr(std::is_integral::value){…}else{…}轻松实现,但是我仅限于C++11,它没有if constexpr 实现这种专门化的好方法是什么?

我正在尝试编写一个签名如下的函数:

template<typename From, typename To>
To bar(From in){...}
模板
禁止(从中){…}
此函数需要具有不同的行为,具体取决于
to
是浮动类型还是整数类型。(假设来自的
为整数,且两者均为算术)

这可以通过使用
if constexpr(std::is_integral::value){…}else{…}
轻松实现,但是我仅限于C++11,它没有
if constexpr


实现这种专门化的好方法是什么?

您可以使用模板重载。e、 g


如果您确定
To
类型为整数或浮点,另一种可能的解决方案是使用标记分派

使用
std::is_integral
继承自
std::true_type
,当
T
为整型时,或从
std::false_type
继承,否则,您可以编写
bar()

template <typename To, typename From>
To bar (From inVal)
 { return foo<To>(inVal, std::is_integral<To>{}); }
template <typename To, typename From>
To foo (From inVal, std::true_type const &)
 { std::cout << "foo() integral case: " << inVal << std::endl; return {0}; }

template <typename To, typename From>
To foo (From inVal, std::false_type const &)
 { std::cout << "foo() float case: " << inVal << std::endl; return {1}; }
现在,打电话

bar<int>("abc");
bar<double>("xyz");

这实际上是我尝试过的,但是,我不喜欢一些无效的东西(例如,bar(“Hello,world!”,6))给出一个神秘的错误。有没有办法实现更好的编译器错误?遗憾的是,
template To bar(From)=delete
不起作用:(另外,切换模板参数的顺序也是个好主意!我想我应该更多地考虑它们的顺序。@Fuzzyzilla您必须将其从重载集中取出。请参阅编辑。
template <typename To, typename From>
To foo (From inVal, std::true_type const &)
 { std::cout << "foo() integral case: " << inVal << std::endl; return {0}; }

template <typename To, typename From>
To foo (From inVal, std::false_type const &)
 { std::cout << "foo() float case: " << inVal << std::endl; return {1}; }
bar<int>("abc");
bar<double>("xyz");
foo() integral case: abc
foo() float case: xyz