【发布时间】:2019-11-22 17:17:23
【问题描述】:
我正在努力为类型转换编写一个通用接口。我更愿意通过模板专业化来实现这一点。我的想法是有一个基本模板实现来抛出异常,即在没有专业化可用的情况下。并且用户应该提供所有可能的转换。
我有一个小实现,当然不能正常工作:)
#include <iostream>
#include <functional>
template <typename T, typename F>
T convert(const F & from)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw ( std::logic_error("Conversion not implemented!") );
}
template<>
int convert<int, std::string >( const std::string & from) {
return 1;
}
int main() {
int a;
std::string b = "hello world";
const std::string &br = b;
a = convert<decltype(a), std::remove_reference_t<std::remove_const_t<decltype(br)>> >(br);
std::cout << a << std::endl;
return 0;
}
我不明白为什么上面的代码不起作用。我正在从br 中删除 const 和引用,因此它应该调用已实现的专业化,但它不会。我期待您的积极回复,以及是否有更有效的方法来调用转换 API 而无需在模板参数中指定类型。
问候, -阿德南
【问题讨论】:
标签: c++ templates types c++17 template-meta-programming