我遇到了一些情况,我必须编写两个函数,其中一个应该使用原始类型调用,std::string
。另一种应该用其他类型来调用。
到目前为止,我以工作解决方案结束:
template <typename...>
struct Void_t_helper {
using type = void;
};
template <typename... Ts>
using Void_t = typename Void_t_helper<Ts...>::type;
template <typename T, typename = void>
struct Is_string : std::false_type {};
template <typename T>
struct Is_string<T, Void_t<decltype (std::declval<T> ().c_str ())>> : std::is_same<decltype (std::declval<T> ().c_str ()), const char*>::type {};
template <typename T>
std::enable_if_t<Is_string<T>::value || std::is_arithmetic<T>::value, void> foo (T) {
std::cout << "string or primitive\n";
}
template <typename T>
std::enable_if_t<!Is_string<T>::value && !std::is_arithmetic<T>::value, void> foo (T) {
std::cout << "other type\n";
}
以及用法:
foo (1);
foo (1.2);
foo (std::string {"fsdf"});
foo (std::vector<int> {1, 2, 3});
foo (std::vector<std::string> {"a", "v", "c"});
按预期产生:
string or primitive
string or primitive
string or primitive
other type
other type
我的问题是:您知道解决此类问题的更好方法吗?
我不太确定是否检查c_str()
存在是我能得到的更好的选择。我知道我可能可以编写一些用于原始类型和std::string
会有一些category_t
用值定义X
,对于其他类型值Y
并使用这个类别来区分这些群体,但我仍然认为c_str()
检查更方便。
我不太确定检查 c_str() 是否存在是否是更好的选择。
理想情况下,您会检查您真正想要的东西。
它可以是一组已知类型或模板,也可以是concept.
目前,您正在检查“具有返回指向常量字符的指针的 c_str() 成员函数的概念”。
问题是,您的 SFINAE 函数需要什么概念?
如果它将使用c_str()
会员,有道理。但是,如果要使用字符串的其他成员或类型,您可能需要构建一个复合概念来描述您将要使用的接口部分。
当然,您可能只是想确认它实际上是一个专业化std::string
。除非您说明用例,否则很难(不可能)判断。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)