【发布时间】:2018-03-18 10:29:32
【问题描述】:
我已将我更困难的问题简化为:
http://coliru.stacked-crooked.com/a/2660b33492651e92
#include <iostream>
#include <string>
#include <type_traits>
template<typename C>
struct get_type
{
C operator()() const = delete;
};
template<>
struct get_type<std::string>
{
std::string operator()() const { return "asd"; }
};
template<>
struct get_type<size_t> {
size_t operator()() const { return 6; }
};
struct S
{
S(){}
template<typename T>
operator T() { return get_type<T>{}(); }
};
struct A
{
A() :s{S{}}, n{S{}} {}
std::string s;
size_t n;
};
int main()
{
A a;
std::cout << "Spock out." << std::endl;
}
这会产生以下错误:
'In instantiation of 'S::operator T() [with T = char]':'...
为什么将 T 推导出为 char 而不是 std::string?
编辑:
@YSC 的回答似乎是正确的: https://stackoverflow.com/a/46608866/4723722
我编辑了帖子以添加解决方案: http://coliru.stacked-crooked.com/a/06d31d981acd2544
struct S
{
S(){}
template<typename T>
explicit operator T() { return get_type<T>{}(); }
};
【问题讨论】:
标签: c++ templates casting template-meta-programming type-deduction