让您的访问者函子从static_visitor<void> 继承,或者只是从typedef void result_type 继承。然后为您的variant 中的每种类型覆盖 —— 这可以通过模板或显式覆盖。
struct my_visitor: static_visitor<void> {
void operator()( a* ) const {
std::cout << "I see an a*\n";
}
void operator()( b* ) const {
std::cout << "I see a b*\n";
}
void operator()( c* ) const {
std::cout << "I see a c*\n";
}
void operator()( std::vector<c*>* ) const {
std::cout << "I see a std::vector<c*>*\n";
}
void operator()( std::vector<b*>* ) const {
std::cout << "I see a std::vector<b*>*\n";
}
void operator()( std::vector<a*>* ) const {
std::cout << "I see a std::vector<a*>*\n";
}
};
顺便说一句,将原始指针存储在boost::variant 中似乎是个坏主意——我想存储智能指针或对象的实例。类似于存储指向std::vector 的指针。有存储原始指针的用例,但它们并不常见。
一个boost::variant< a, b, c, std::vector<a>, std::vector<b>, std::vector<c> >,或者如果你的类型是多态接口,std::shared_ptr 相同(最后我检查了boost::variant 没有移动感知,所以std::unique_ptr 不能很好地工作)。
想象一下,如果您只想忽略 std::vector 实例;
结构 my_visitor: static_visitor {
无效运算符()(一*)常量{
std::cout
// container traits class, detects if `std::begin` and `std::end` work on an instance of the data:
template<typename C, bool=true>
struct is_container:std::false_type {};
template<typename C>
struct is_container<C, std::is_same< std::begin(std::declval<C&>()), std::end(std::declval<C&>()) >::value>:
std::true_type
{};
struct my_visitor: boost::static_visitor<void> {
// blah blah blah
// SFINAE detection of C being a container:
template<typename C>
typename std::enable_if< is_container<C>::value >::type operator()( C* ) const {
std::cout << "I see a Container<?>*\n";
}
};
在 C++11 编译器中。