gpt4 book ai didi

c++ - 当模板类 is_convertible 为众所周知的类型时,特化仿函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:35 25 4
gpt4 key购买 nike

所以我想在模板类型boost::is_convertible时应用特定代码至 WellKnownType :

template <typename T>
class Foo {
public:
Foo() {
// apply specific function to m_t
// if T is convertible to WellKnownType
}
T m_t;
};

为此,我想到了使用仿函数:

template <typename T>
struct my_functor {
void operator()(T& t) {
// do nothing by default
}
};

然后,我想在 boost::is_convertible<T, WellKnownType> 时特化这​​个仿函数来做其他事情。 :

template <>
struct my_functor<...> {
void operator()(T& t) {
// do something to t because it is convertible to WellKnownType
}
};

然后,我想我可以很容易地改变FooT 时使用仿函数并做某事的定义可转换为 WellKnownType不存在时什么也不做:

template <typename T>
class Foo {
public:
Foo() {
my_functor<T>()(m_t);
}
T m_t;
};

我不知道如何实现这种行为。我知道 BOOST_CONCEPT_REQUIRES ,但无法弄清楚如何将其应用于模板特化。有帮助吗?

最佳答案

你可以用你的仿函数做一些事情

template<typename T, typename WellKnownType >
struct my_functor
{
void operator()( const T& x) {
myopImpl(x, boost::is_convertible<T, WellKnownType>() );
}

void myopImpl(T const& x, boost::false_type)
{ std::cout << "Some Other Stuff \n"; }

void myopImpl(T const& x, boost::true_type)
{ std:: cout << "Some Specific Stuff \n"; }

};

Demo here

关于c++ - 当模板类 is_convertible 为众所周知的类型时,特化仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32675379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com