启用swapSTL算法的正确方法是什么?
1)会员swap.是否std::swap使用SFINAE技巧来使用该成员swap.
2)自由站立swap在同一名称空间中.
3)部分专业化std::swap.
4)以上所有.
谢谢.
编辑:看起来我没有清楚地说出我的问题.基本上,我有一个模板类,我需要STL algos来使用我为该类编写的(高效)交换方法.
我是一名Java开发人员,我对C++很陌生.我需要实现某种实用类,我正在考虑将这些方法实现为static.但是,我遇到了关于命名空间函数与静态方法的stackoverflow问题,并且显然名称空间函数是首选方法.所以我想知道如果有关于如何实现命名空间功能的任何文章或示例.例如,我应该如何在头文件中声明命名空间函数?头文件是否只包含类头文件等函数定义,实现应该在cpp文件中,还是我应该直接在头文件中实现函数?
基本上,我试图实现一个应用程序来解析包含一些命令的文本文件.所以我正在考虑实现静态辅助方法来处理文本处理.例如readCommand(字符串行).如果我的方向错误,请告诉我.谢谢
我对私人方法和功能有疑问.假设我有一些不必在类中的实用方法.但是那些相同的方法需要调用我不想向用户公开的其他方法.例如:
Suspect.h
namespace Suspect {
/**
* \brief This should do this and that and more funny things.
*/
void VerbalKint(void); // This is for you to use
}
Run Code Online (Sandbox Code Playgroud)
Suspect.cpp
namespace Suspect {
namespace Surprise {
/**
* \brief The user doesn't need to be aware of this, as long
* the public available VerbalKint does what it should do.
*/
void KeyserSoze(void) {
// Whatever
}
} // end Surprise
void VerbalKint(void) {
Surprise::KeyserSoze();
}
}
Run Code Online (Sandbox Code Playgroud)
所以,这种布局是有效的.包含时Suspect.h,只有 …
假设我需要将传入数据写入云上的数据集。我何时、何地以及是否需要在代码中使用数据集,取决于传入的数据。我只想获取对数据集的引用一次。实现这一目标的最佳方法是什么?
启动时初始化为全局变量并通过全局变量访问
if __name__="__main__":
dataset = #get dataset from internet
Run Code Online (Sandbox Code Playgroud)这看起来是最简单的方法,但即使从不需要它也会初始化该变量。
第一次需要数据集时获取引用,保存在全局变量中,并通过get_dataset()方法访问
dataset = None
def get_dataset():
global dataset
if dataset is none
dataset = #get dataset from internet
return dataset
Run Code Online (Sandbox Code Playgroud)第一次需要数据集时获取参考,保存为函数属性,并通过get_dataset()方法访问
def get_dataset():
if not hasattr(get_dataset, 'dataset'):
get_dataset.dataset = #get dataset from internet
return get_dataset.dataset
Run Code Online (Sandbox Code Playgroud)任何其他方式
我有一个带有内联函数的命名空间,如果有多个源文件,它将被使用.尝试链接我的应用程序时,内联函数将报告为重复符号.似乎我的代码不会内联函数,我想知道这是否是预期的行为以及如何最好地处理它.
我使用以下gcc选项:-g -Wextra -pedantic -Wmissing-field-initializers -Wredundant-decls -Wfloat-equal -Wno-reorder -Wno-long-long相同的代码样式似乎在构建时正确编译和链接一个VC7环境.
以下代码示例显示了代码的结构:
/* header.h */
namespace myNamespace {
inline bool myFunction() {return true;}
}
/* use_1.cpp */
#include "header.h"
...
bool OK = myNamespace::myFunction();
...
/* use_2.cpp */
#include "header.h"
...
bool OK = myNamespace::myFunction();
...
Run Code Online (Sandbox Code Playgroud) 最近我一直在尝试更好地理解在 C++ 中使用工厂模式。
我查阅了以下资源:
https://www.geeksforgeeks.org/design-patterns-set-2-factory-method/
https://sourcemaking.com/design_patterns/factory_method/cpp/1
https://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
https://www.bogotobogo.com/DesignPatterns/factorymethod.php
https://gist.github.com/pazdera/1099562
https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns
在有人将其标记为“不是问题”之前,我确实有一些明确的问题,我稍后会讨论。但为了首先澄清我到目前为止的理解,我想从一个例子开始。这是我从上述链接中的信息中得到的最好的例子(最好的含义说明了工厂模式,但尽可能简单,因此该模式的初学者可以清楚地看到所涉及的问题):
// FactoryPattern.cpp
#include <iostream>
#include <vector>
enum AnimalSpecies { dog, cat };
class Animal
{
public:
virtual void makeSound() = 0;
};
class Dog : public Animal
{
public:
void makeSound() { std::cout << "woof" << "\n\n"; }
};
class Cat : public Animal
{
public:
void makeSound() { std::cout << "meow" << "\n\n"; }
};
class AnimalFactory
{
public:
static Animal* makeAnimal(AnimalSpecies animalSpecies);
};
Animal* AnimalFactory::makeAnimal(AnimalSpecies animalSpecies) …Run Code Online (Sandbox Code Playgroud) 可能重复:
命名空间+函数与类上的静态方法
我想将类似的功能组合起来.我可以用两种方式之一做.对我来说,它们只是语法上的差异......最后它并不重要.这个观点准确吗?
命名空间:
namespace util
{
void print_array(int array[])
{
int count = sizeof( array ) / sizeof( array[0] );
for (int i = 0; i <= count; i++) cout << array[i];
}
}
Run Code Online (Sandbox Code Playgroud)
类:
class Util
{
public:
static void print_array(int array[])
{
int count = sizeof(array);
for (int i = 0; i <= count; i++) cout << array[i];
}
};
Run Code Online (Sandbox Code Playgroud)
打电话给
Util::print_array() // Class
Run Code Online (Sandbox Code Playgroud)
要么
util::print_array() // Namespace
Run Code Online (Sandbox Code Playgroud) 在C#中我创建了一个静态类,它有许多我可以直接调用的数学辅助函数而无需创建类的实例.我似乎无法在C++中使用它.
例如,如果该类被称为MathsClass并且有一个名为MultiplyByThree的函数,那么我会像这样使用它:
float Variable1 = MathsClass.MultiplyByThree(Variable1);
Run Code Online (Sandbox Code Playgroud)
在我的代码的C++版本中,我收到错误:
'MathsClass' : illegal use of this type as an expression
Run Code Online (Sandbox Code Playgroud)
和
error C2228: left of '.MultiplyByThree' must have class/struct/union
Run Code Online (Sandbox Code Playgroud)
我如何编写C#静态类的C++等价物来提供这种功能?
我在c ++应用程序中看到过一次只使用带有头文件和源文件的命名空间声明,如下所示:
#ifndef _UT_
#define _UT_
#include <string>
#include <windows.h>
namespace UT
{
void setRootPath(char* program_path, char* file_path);
char * ConvertStringToCharP(std::string str);
};
#endif
//and then in UT.cpp
#include "UT.h"
namespace UT
{
char * ConvertStringToCharP(std::string str)
{
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0';
return writable;
}
void setRootPath(char* program_path, char* file_path)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
比使用静态方法定义经典类更好吗?
还是只是简单的课程?
剂量这种方法对编译器链接器有什么好处?
此命名空间中的方法被称为分配.
我想有一个只包含公共函数的类,例如:
class foo
{
public:
int f1(param1, param2) ;
void f2(param1, param2);
};
Run Code Online (Sandbox Code Playgroud)
Class没有状态,它只是操纵输入参数,行为像辅助类,
这是一个好的设计吗?还是需要特殊模式?模式的名称是什么?
这是一个关于理解设计决策的问题,而不是对错误或缺陷的抱怨。
在C++标准库中,创建共享指针及其对象的函数是直函数,
template< class T, class... Args> std::shared_ptr<T> make_shared( Args&&... args );
Run Code Online (Sandbox Code Playgroud)
为什么这个函数不是static的函数shared_ptr<T>,如下所示:
template <class... Args> std::shared_ptr<T>::make(Args&&... args);
Run Code Online (Sandbox Code Playgroud)
这将使std::命名空间更加整洁,并且还允许这样的事情:
using shared_vector = std::shared_ptr<std::vector<int>>;
shared_vector a = shared_vector::make(7);
Run Code Online (Sandbox Code Playgroud) 函数如下:
float random_float(float min, float max)
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_real_distribution<> distr((double)min, (double)max); // define the range
return (float)distr(gen);
}
Run Code Online (Sandbox Code Playgroud)
我想避免每次调用此函数时调用前 3 行。我也不想用构造函数创建一个类,然后每次我只想生成一个随机数时都必须实例化它。我不太熟悉现代 C++ 特性的可能性,所以我想要一些想法。
我想创建一个C++类,它只与静态函数合并,无论如何都可以使用.我创建了一个.h包含声明的.cpp文件和一个包含定义的文件.但是,当我在我的代码中使用它时,我收到一些奇怪的错误消息,我不知道如何解决.
这是我的Utils.h文件的内容:
#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
#include <vector>
#include <opencv/cv.h>
#include <opencv/cxcore.h>
class Utils
{
public:
static void drawPoint(Mat &img, int R, int G, int B, int x, int y);
};
Run Code Online (Sandbox Code Playgroud)
这是我的Utils.cpp文件的内容:
#include "Utils.h"
void Utils::drawPoint(Mat &img, int R, int G, int B, int x, int y)
{
img.at<Vec3b>(x, y)[0] = R;
img.at<Vec3b>(x, y)[1] = G;
img.at<Vec3b>(x, y)[2] = B; …Run Code Online (Sandbox Code Playgroud) c++ ×12
namespaces ×3
algorithm ×1
c++17 ×1
duplicates ×1
gcc ×1
inline ×1
opencv ×1
python ×1
shared-ptr ×1
stl ×1
swap ×1