【发布时间】:2019-09-28 01:11:32
【问题描述】:
我正在尝试检测我的函数的特定重载是否可调用。我以为我可以做类似于this answer 的事情,但我认为问题在于函数签名template<typename From, typename To> convert(const From&) 定义明确,但实例化不是。
#include <iostream>
#include <string>
template<typename From, typename To>
To convert(const From& from)
{
// I have a lot of additional template specializations for this function
return from;
}
template<typename From, typename To>
struct IsConvertible
{
template<typename = decltype(convert<From, To>(From()))>
static std::true_type test(int);
template<typename T>
static std::false_type test(...);
static bool const value = decltype(test(0))::value;
};
int main()
{
std::cout << "IsConvertible=" << IsConvertible<int, float>::value << std::endl;
// Returns 1 as expected
std::cout << "IsConvertible=" << IsConvertible<int, std::string>::value << std::endl;
// Returns 1, expected 0. The issue seems to be that decltype(convert<From, To>(From()))
// is somehow ok, although convert<int, std::string>(1) definitly isn't
}
我想使用IsConvertible 进行一些额外的元编程。 是否可以检测到template<typename From, typename To> To convert(const From&) 函数是否真的可以调用?`
【问题讨论】:
-
没有。这被称为 SFINAE 不友好。
-
我的 2 美分:我尝试了 coliru,因为我很难相信...Live Demo on coliru。
-
这不是超载,而是专业化。您可以检测是否存在重载,但您无法检测是否存在特化。使用重载。
-
我不确定要详细说明什么。不要使用模板特化进行转换,使用重载。一个小问题是你不能重载返回类型,但这很容易用标签类型修复。
标签: c++ c++11 templates metaprogramming template-meta-programming