ttu*_*chi 5 c++ templates boost boost-any
我正在尝试存储和操作具有不同参数类型的模板类对象列表; 模板类有两个parametrised方法,一个返回参数类型和一个空隙一个接受它作为输入.
更具体地说,我有一个模板类,定义如下:
template<typename T>
class Test
{
public:
virtual T a() = 0;
virtual void b(T t) = 0;
};
Run Code Online (Sandbox Code Playgroud)
和它的不同规格,如:
class TestInt : public Test<int>
{
public:
int a() {
return 1;
}
void b(int t) {
std::cout << t << std::endl;
}
};
class TestString : public Test<std::string>
{
public:
std::string a() {
return "test";
}
void b(std::string t) {
std::cout << t << std::endl;
}
};
Run Code Online (Sandbox Code Playgroud)
我希望能够在一个列表中存储两者的不同对象TestInt并TestString键入并循环调用一个方法作为另一个方法的输入,如:
for (auto it = list.begin(); it != list.end(); ++it)
(*it)->b((*it)->a());
Run Code Online (Sandbox Code Playgroud)
我已经研究过boost::any但是我无法将迭代器强制转换为特定的类,因为我不知道每个存储对象的具体参数类型.也许这不能用像C++这样的静态类型语言来完成,但我想知道是否可以解决这个问题.
仅仅为了完整起见,我要补充一点,我的总体目标是开发一个"参数化观察者",即能够用不同的参数定义观察者(与观察者模式一样):Test类是观察者类,而不同类型的观察员,我试图以正确定义的列表存储在主题类,它会通知他们全部通过这两种方法中a()和b().
虚拟在这里实际上没有任何意义,因为每个T签名都是不同的。
所以看来你有永恒的“我们如何模拟虚拟函数模板”或“如何创建没有虚拟函数的接口”的另一个版本:
第一个基本上包含您可以在这里使用的想法。
这是我会做什么的想法:
#include <algorithm>
#include <iostream>
namespace mytypes {
template <typename T>
struct Test {
T a() const;
void b(T t) { std::cout << t << std::endl; }
};
template <> int Test<int>::a() const { return 1; }
template <> std::string Test<std::string>::a() const { return "test"; }
using TestInt = Test<int>;
using TestString = Test<std::string>;
}
#include <boost/variant.hpp>
namespace mytypes {
using Value = boost::variant<int, std::string>;
namespace detail {
struct a_f : boost::static_visitor<Value> {
template <typename T>
Value operator()(Test<T> const& o) const { return o.a(); }
};
struct b_f : boost::static_visitor<> {
template <typename T>
void operator()(Test<T>& o, T const& v) const { o.b(v); }
template <typename T, typename V>
void operator()(Test<T>&, V const&) const {
throw std::runtime_error(std::string("type mismatch: ") + __PRETTY_FUNCTION__);
}
};
}
template <typename O>
Value a(O const& obj) {
return boost::apply_visitor(detail::a_f{}, obj);
}
template <typename O, typename V>
void b(O& obj, V const& v) {
boost::apply_visitor(detail::b_f{}, obj, v);
}
}
#include <vector>
int main()
{
using namespace mytypes;
using AnyTest = boost::variant<TestInt, TestString>;
std::vector<AnyTest> list{TestInt(), TestString(), TestInt(), TestString()};
for (auto it = list.begin(); it != list.end(); ++it)
b(*it, a(*it));
}
Run Code Online (Sandbox Code Playgroud)
这打印
1
test
1
test
Run Code Online (Sandbox Code Playgroud)
如果您坚持,您可以将AnyTest变体包装到适当的类中,并在其上拥有成员函数a():b(...)
int main()
{
using namespace mytypes;
std::vector<AnyTest> list{AnyTest(TestInt()), AnyTest(TestString()), AnyTest(TestInt()), AnyTest(TestString())};
for (auto it = list.begin(); it != list.end(); ++it)
it->b(it->a());
}
Run Code Online (Sandbox Code Playgroud)