我想出了以下代码,在编译时检测继承的函数是否在派生类中被覆盖。它适用于所有主要编译器 - gcc/clang/msvc。但是这种方法实际上得到了标准的支持吗?
#include <type_traits>
struct B {
virtual void f1() {}
virtual void f2() {}
void f3() {}
void f4() {}
};
struct D: B {
void f1() override {}
void f3() {}
};
int main()
{
static_assert(!std::is_same_v<decltype(&B::f1), decltype(&D::f1)>, "overriden");
static_assert(std::is_same_v<decltype(&B::f2), decltype(&D::f2)>, "base");
static_assert(!std::is_same_v<decltype(&B::f3), decltype(&D::f3)>, "overriden");
static_assert(std::is_same_v<decltype(&B::f4), decltype(&D::f4)>, "base");
return 0;
}
Run Code Online (Sandbox Code Playgroud) 以下代码不能在 clang 3.5+ 中编译,但可以在所有 gcc 版本和 clang < 3.5 中编译。
struct Logger {
template <class T>
Logger& operator<<(const T& /*val*/)
{
// m_buf << val;
return *this;
}
};
struct Value {
template <class Stream>
friend Stream& operator<<(Stream& os, const Value& /*val*/)
{
// os << m_val;
return os;
}
};
int main()
{
Logger logger;
Value value;
logger << value;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
叮当错误是
<source>:23:12: error: use of overloaded operator '<<' is ambiguous (with operand types 'Logger' and 'Value') …
Run Code Online (Sandbox Code Playgroud) 以下代码在 boost::property_tree::read_xml() 调用时因段错误而崩溃。仅当在使用 boost::asio::spawn() 生成的 io_service 处理程序内部调用它时,才会发生这种情况。如果处理程序刚刚发布,则可以正常工作。有解决办法或解决方法吗?(提升1.61)
#include <boost/asio/spawn.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
#include <sstream>
#include <thread>
void process()
{
std::cerr << "start"<< std::endl;
std::istringstream is("<t>1</t>");
boost::property_tree::ptree pt;
boost::property_tree::read_xml(is, pt); // <<< seg fault here
std::cerr << std::endl << "end" << std::endl;
}
int main()
{
boost::asio::io_service io_service;
boost::asio::spawn(io_service, [] (boost::asio::yield_context y){
process();
});
io_service.run();
return 0;
}
Run Code Online (Sandbox Code Playgroud)