我正在使用boost :: program_options库来处理命令行参数.我需要通过-r选项接受文件名,万一它是空的(-r没有params)我需要使用stdin.
desc.add_options()
("replay,r", boost::program_options::value<std::string>(), "bla bla bla")
Run Code Online (Sandbox Code Playgroud)
在这种情况下,boost不会接受-r而没有params并抛出异常.default_value()选项不起作用,即使用户没有给出-r选项,它也会使库返回值.
任何想法如何解决?
请考虑以下代码:
#include <iostream>
namespace ns1
{
struct A
{
};
template <class T>
std::ostream& operator << (std::ostream& os, const T& t)
{
return os << "ns1::print" << std::endl;
}
}
namespace ns2
{
template <class T>
std::ostream& operator << (std::ostream& os, const T& t)
{
return os << "ns2::print" << std::endl;
}
void f (const ns1::A& a)
{
std::cout << a;
}
}
int main()
{
ns1::A a;
ns2::f (a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据标准,编译失败并出现"模糊过载错误".
但为什么?当然,A''home'命名空间中"同样好"的运算符应该优先?有没有合理的理由不这样做?
c++ templates namespaces language-lawyer overload-resolution
考虑这个例子(https://ideone.com/RpFRTZ)
这将Foo::comp (const Foo& a)使用不相关类型的参数进行有效调用Bar.这不仅编译,如果我注释std::cout << "a = " << a.s << std::endl;它也以某种方式工作和打印Result: 0
如果我打印出值,而不是段错误,这是公平的......但为什么它首先编译?
#include <functional>
#include <string>
#include <iostream>
struct Foo
{
bool comp(const Foo& a)
{
std::cout << "a = " << a.s << std::endl;
return a.s == s;
}
std::string s;
};
struct Bar
{
int a;
};
template <class F, class T>
void execute (F f, T a)
{
std::cout << "Result: " << f (a) …Run Code Online (Sandbox Code Playgroud) 如何强制编译器为基类选择模板函数重载?
这是一个说明问题的例子
#include <iostream>
class A
{};
class B : public A
{};
template <class T>
void f (const T& t)
{
std::cout << "Generic f" << std::endl;
}
void f (const A& a)
{
std::cout << "Overload for A" << std::endl;
}
template <class T>
void call_f (const T& t)
{
f (t);
}
int main()
{
call_f (10);
call_f (A());
call_f (B());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它产生输出
Generic f
Overload for A
Generic f
Run Code Online (Sandbox Code Playgroud)
为什么编译器f (const A&)在第三种情况下没有接收? …