gpt4 book ai didi

c++ - 如何使用匿名模板参数强制模板参数类从 super 派生

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:21 30 4
gpt4 key购买 nike

我有几个模板类

template < class Cost >
class Transition {
public:
virtual Cost getCost() = 0;
};

template < class TransitionCl, class Cost >
class State {
protected:
State(){
static_assert(
std::is_base_of< Transition< Cost >, TransitionCl >::value,
"TransitionCl class in State must be derived from Transition< Cost >"
);
}
public:
virtual void apply( const TransitionCl& ) = 0;
};

而且我宁愿不必将 Cost 传递给 State,因为 State 完全独立于 Cost ,但我想确保 TransitionCl 实现了 Transition 接口(interface)。

有没有办法在第二个模板中使 Cost 匿名,从而在声明新的 State 类时不必传递它?

作为引用,我使用的是 g++ -std=c++14 [source file]

编辑:我发布了问题的改写版本(希望更清晰)并收到了最佳答案 here

最佳答案

根据我从您的问题中了解到的情况,我有一个快速的解决方案:

template < class Cost >
class Transition {
public:
virtual Cost getCost() = 0;
};

template <typename T>
class Der : public Transition<T>
{
public:
T getCost() override {
}
};

template < class Transition >
class State;

template <template <typename> class TransitionCl, typename Cost>
class State <TransitionCl<Cost>> {
public:
State(){
static_assert(
std::is_base_of< Transition< Cost >, TransitionCl<Cost> >::value,
"TransitionCl class in State must be derived from Transition< Cost >"
);
}
};

int main()
{
Der<int> d;
State<decltype(d)> s;

return 0;
}

在上面的示例中,您不必在创建 State 对象时传递 'Cost' 类型。

=====更新======

template <typename Cost>
class Transition
{
public:
virtual Cost getCost() = 0;
virtual ~Transition() {}
};

class TD: public Transition<int>
{
public:
int getCost() override {
std::cout << "getCost override" << std::endl;
return 42;
}
};

namespace detail {
template <typename T>
struct is_base_of_cust {
// This is a bit hacky as it is based upon the internal functions
// (though public) of the Transition class.
using CostType = decltype(std::declval<T>().getCost());
static const bool value = std::is_base_of<Transition<CostType>, T>::value;
};
};

template <class TransitionCl>
class State
{
protected:
State() {
static_assert(
detail::is_base_of_cust<TransitionCl>::value,
"TransitionCl class in State must be derived from Transition<Cost>"
);
}
public:
virtual void apply(const TransitionCl&) = 0;
virtual ~State() {}
};


class StateImpl: public State<TD>
{
public:
void apply(const TD&) override {
std::cout << "StateImpl::apply" << std::endl;
}
};


int main() {
StateImpl impl;
return 0;
}

关于c++ - 如何使用匿名模板参数强制模板参数类从 super 派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34670375/

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