是否可以使用标记调度来确定返回类型
Is it possible to use tag dispatching to determine return type
标签调度是在模板的Switch传递类型中提到的。
有可能(以及如果有可能的话如何)做这样的事情吗:
struct Tag1 {};
struct Tag2 {};
template<class T, typename R>
R get();
template<>
double get<Tag1>() {return 1.3;}
template<>
char const *get<Tag2>() {return "hello";}
double aDouble = get<Tag1>();
char const *aString = get<Tag2>();
上面的代码导致编译器抱怨对重载函数的调用不明确,但我希望最后两行能传达使用意图。
Thx
您可以使用std::enable_if
和std::is_same
(C++11),或者它们的增强等价物:
template <typename Tag>
typename std::enable_if<std::is_same<Tag, Tag1>::value, double>::type get()
{ ... }
template <typename Tag>
typename std::enable_if<std::is_same<Tag, Tag2>::value, char const *>::type get()
{ ... }
具有不同数量模板参数的函数模板会相互重载,因此您不是在定义专业化,而是在定义重载。像这样的东西应该起作用:
struct Tag1 {};
struct Tag2 {};
template<class T> struct MapResult;
template<> struct MapResult<Tag1> { typedef double Result; };
template<> struct MapResult<Tag2> { typedef char const* Result; };
template<class T>
typename MapResult<T>::Result get();
template<> double get<Tag1>() {return 1.2;}
template<> char const *get<Tag2>() {return "hello";}
get
的第二个模板参数无法推导,因为它只作为返回类型出现:谁能说get<Tag1>()
是对get<Tag1, double>
的调用,而不是例如get<Tag1, int>
?如果要调用例如get<Tag1, double>()
,则该调用将被解析为正确的专业化。
然而,我怀疑您并不是真的希望get
是一个具有两个模板参数的函数模板:返回类型可能是第一个参数的函数。因此,我建议您这样申报get
:
namespace result_of {
template<typename T>
struct get;
}
template<typename T>
typename result_of::get<T>::type get();
其中CCD_ 10将是计算期望结果类型的元函数。为了更简单,我们将把所有的鸡蛋放在result_of::get
篮子里,而不是专门化函数模板get
:
namespace result_of {
template<typename T>
struct get;
}
template<typename T>
typename result_of::get<T>::type get()
{ return result_of::get<T>::apply(); }
namespace result_of {
template<>
struct get<Tag1> {
typedef double type;
static type apply()
{ return 1.3; }
};
template<>
struct get<Tag2> {
typedef const char* type;
static type apply()
{ return "hello"; }
};
}
一般来说,专门化类模板比专门化函数模板更为常见,而且在需要专门化函数样板的情况下,通常会让函数样板将其实现完全委托给类样板,从而使其变得更简单。
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 为什么返回类型中需要typename?C++
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 推导 std::vector::back() 的返回类型
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 是否可以使用标记调度来确定返回类型
- 尾随返回类型和标记调度