也许我错过了一些明显的东西,但是下面的编译和运行,我不知道为什么.我知道这一点,但在下面的示例中,参数包的位置和默认参数是相反的.它是否违反了默认参数必须最后出现的规则?参数包不能具有默认值.
#include <iostream>
#include <string>
#include <tuple>
template<typename ... Ts>
struct Test
{
int i;
std::string str;
Test(int _i = 0, Ts&& ... _ts)
:
i(_i),
str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
{}
};
int main()
{
Test<std::string> t(1, "huh??");
std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这产生了
t.i = 1, t.str = huh??
Run Code Online (Sandbox Code Playgroud) 这个问题(松散地)与我昨天在这里提出的问题有关.
我刚刚重构了一个容器类(Ecosystem),它包含指向Individuals的指针:
class Ecosystem
{
// This is an interface class providing access
// to functions in Individual without exposing
// the Individual class.
// It performs global operations on the entire ecosystem
// (like sorting individuals based on certain criteria)
// but is also capable of invoking functions from the
// Individual class.
// It also holds the global configuration for this ecosystem.
private:
Config config;
std::map<int, std::shared_ptr<Individual> > individuals;
public:
Ecosystem() {}; …Run Code Online (Sandbox Code Playgroud) 我有一些小的头文件库(仅头部部分很重要).在初始版本中,我在其中定义的类中有一些静态成员.直到后来(当我在一个更大的项目中使用它们时)我才发现静态成员会违反ODR.我想让它们只保留头文件,因此在一个单独的.cpp文件中定义静态成员是不可能的.一个众所周知的解决方案是为每个静态成员使用Meyers单例函数 - 局部静态变量(例如,如此处所示).
这一切都很好,但由于我希望单例表现得像一个成员变量,我希望能够使用setter和getter来获取和设置值.但是Meyers单例功能的局部静态变量看起来像是什么?我无法找到任何特定问题的解决方案.
澄清一下,这些是要求:
编辑1:
我想解释一下为什么你可能需要这个.
我提到的库中的静态变量定义了一些参数的默认值.但是,我想让用户选择在程序开头设置默认值,而不是硬编码这些默认值,这样他们就不必在每次调用成员函数或构造一个函数时手动传递值.新实例.
此外,虽然我同意在这里提供的示例中使用术语"Meyers singleton"具有误导性(我只是使用了一个int值),但是没有什么能阻止您使用这个范例而只需要一个自定义类的例子.在这种情况下,"Meyers singleton"一词是合理的.
编辑2:
这与inline staticC++ 17中的变量引入有些无关,但我会把它留给那些没有选择使用C++ 17的人.