有没有一种方法可以根据模板参数自动在多个非模板函数之间进行选择?
例子:
class Aggregate
{
public:
std::string asString();
uint32_t asInt();
private:
// some conglomerate data
};
template <typename T>
T get(Aggregate& aggregate)
{
// possible map between types and functions?
return bind(aggregate, typeConvert[T])(); ??
// or
return aggregate.APPROPRIATE_TYPE_CONVERSION();
}
如果没有好的转换可用,则抛出编译器错误的解决方案会很好,即
get<double>(aggregate); // compile error
我不想使用模板特化,即
template<>
int get(Aggregate& aggregate)
{
return aggregate.asInt();
}
因为当你的 get() 函数有多于一行代码时,它会导致代码重复
最佳答案
行人方式是分别定义每个可能的选项:
template <typename T> T get(Aggregate &); // leave undefined
template <> uint32_t get(Aggregate & a) { return a.asInt(); }
// ...
没有任何更系统的结构来编码哪个函数服务于哪个转换,我认为这是你能做的最好的。不过,可能值得重新定义 Aggregate
,以便更加自省(introspection)。
关于c++ - 根据模板参数选择函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22813889/