the*_*dal 2 c++ templates types template-meta-programming c++17
我正在努力编写一个用于类型转换的通用接口。我希望通过模板专门化来实现。我的想法是要有一个基本的模板实现来引发异常,即在没有专门化的情况下。用户应该提供所有可能的转换。
我有一个小的实现,当然是行不通的:)
#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;
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么上面的代码无法正常工作。我正在从中删除const和reference br,因此它应该调用已实现的专业化,但不是。我期待您的积极答复,也希望有一种更有效的方法来调用convert API,而无需在模板参数中指定类型。
此致-Adnan
I am removing const and reference from the br
Yes, but in the wrong order.
You remove before const and after reference; you should remove reference before and const after
// ......................................................VVVVVVVVV reference before
a = convert<decltype(a), std::remove_const_t<std::remove_reference_t<decltype(br)>> >(br);
// ..................................^^^^^ const after
Run Code Online (Sandbox Code Playgroud)
The point is that decltype(br) is std::string const &; I mean: const is applied only to std::string, not to std::string &.
On the contrary, the reference is applied to std::string const.
So when you apply std::remove_const to std::string const &, you get again std::string const &, because the full type isn't const.
Next you apply std::remove_reference to std::string const & and you get std::string const.
So the const remain.
If you use first std::remove_reference, from std::string const & you obtain std::string const.
Then you use std::remove_const (this time works, because the full type is const) and you get std::string.